/**
 * 初始化性能监控
 */
export const initPerformanceTracking = () => {
  if (typeof window !== 'undefined' && 'PerformanceObserver' in window) {
    // 监控关键性能指标
    const perfObserver = new PerformanceObserver((entries) => {
      entries.getEntries().forEach((entry) => {
        const metric = {
          name: entry.name,
          type: entry.entryType,
          startTime: entry.startTime,
          duration: entry.duration,
          details: entry.toJSON()
        };
        
        // 发送到监控服务
        sendMetricsToAnalytics(metric);
      });
    });

    // 监控类型
    perfObserver.observe({ entryTypes: [
      'navigation',      // 页面导航
      'resource',        // 资源加载
      'paint',           // FP/FCP
      'measure',         // 自定义测量
      'longtask'        // 长任务
    ] });
  }
};

/**
 * 发送指标到分析服务
 * @param {Object} metric 
 */
const sendMetricsToAnalytics = (metric) => {
  // 这里实现实际的发送逻辑，可以使用fetch或专门的分析SDK
  console.log('[Performance Metric]', metric);
  // 示例: fetch('/analytics', { method: 'POST', body: JSON.stringify(metric) });
};

/**
 * 手动测量代码段性能
 * @param {string} name - 测量名称
 * @param {function} callback - 要测量的函数
 */
export const measurePerformance = (name, callback) => {
  if (typeof performance !== 'undefined' && performance.mark) {
    performance.mark(`${name}-start`);
    const result = callback();
    performance.mark(`${name}-end`);
    performance.measure(name, `${name}-start`, `${name}-end`);
    return result;
  }
  return callback();
};

/**
 * Web Vitals监控
 */
export const initWebVitals = (onReport) => {
  if (typeof onReport !== 'function') return;

  import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
    getCLS(onReport);
    getFID(onReport);
    getFCP(onReport);
    getLCP(onReport);
    getTTFB(onReport);
  });
};
